from rest_framework.decorators import api_view
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework import viewsets
from rest_framework import generics, permissions
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope, TokenHasScope

from django.contrib.auth.models import User, Group
from userApp.models import Student
from userApp.serializers import StudentSerializer, UserSerializer, GroupSerializer

# Create your views here.
class StudentViewSet(viewsets.ModelViewSet):
    """
    查看学生的信息
    """
    queryset = Student.objects.all()
    serializer_class = StudentSerializer


@api_view(['GET', 'POST'])
def stu_list(request):
    """
    获取已存在的所有学生的信息/新建一个学生信息
    """
    if request.method == 'GET':
        student = Student.objects.all()
        serializer = StudentSerializer(student, many=True,
                context={'request': request})
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = StudentSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data,
                    status=status.HTTP_201_CREATED)
        return Response(serializer.errors,
                status=status.HTTP_400_REQUEST)

@api_view(['GET', 'PUT', 'DELETE'])
def stu_detail(request, pk):
    """
    Retrieve, update or delete a stu instance.
    """
    try:
        student = Student.objects.get(pk=pk)
    except Student.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = StudentSerializer(student)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = StudentSerializer(student, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        student.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


class UserList(generics.ListCreateAPIView):
    permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
    queryset = User.objects.all()
    serializer_class = UserSerializer

class UserDetails(generics.RetrieveAPIView):
    permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
    queryset = User.objects.all()
    serializer_class = UserSerializer

class GroupList(generics.ListAPIView):
    permission_classes = [permissions.IsAuthenticated, TokenHasScope]
    required_scopes = ['groups']
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
